py = import('python')
venv_py = join_paths(meson.project_source_root(), 'venv', 'bin', 'python3')
python3 = py.find_installation(venv_py, modules: ['mako'], required: false)
if not python3.found()
  python3 = py.find_installation('python3', modules: ['mako'], required: true)
endif
libmcpp_dep = dependency('libmcpp', fallback: ['libmcpp','libmcpp_dep'], default_options: ['tests=false'], required: true)

subdir('devices')
subdir('network')

# protocol 是单文件模块，直接在此生成
out_dir = meson.current_build_dir()
inc     = include_directories('.')
inc_mcpy = include_directories('../../include')

# 让生成阶段能找到 mcpy 包
mcpy_env = environment({ 'PYTHONPATH': meson.project_source_root() })

# 当生成器或模板变化时，强制重新生成
mcpy_codegen_files = files()

protocol_py   = files('protocol.py')
protocol_name = 'protocol'

# 构造命令行参数
cmd_args = [
    python3,
    '-m', 'mcpy.cli',
    '@INPUT@',
    '-o', out_dir,
    '--tag', protocol_name,
    '--emit-depfile', 'protocol.d',
    '--format', get_option('format').to_string(),
]

proto_gen = custom_target(
  'gen_' + protocol_name,
  input: protocol_py,
  output: [ '@0@.cpp'.format(protocol_name), '@0@.h'.format(protocol_name), '@0@.pyi'.format(protocol_name) ],
  command: cmd_args,
  env: mcpy_env,
  depfile: 'protocol.d',
  depend_files: mcpy_codegen_files,
  build_by_default: true,
)

shared_library(
  protocol_name,
  [ proto_gen[0] ],
  include_directories: [inc, inc_mcpy],
  dependencies: [libmcpp_dep],
  cpp_args: ['-fPIC', '-Wall'],
)

# 子目录（已在文件顶部引入，此处移除重复）